<?php

namespace App\Http\Controllers\Circle;

use App\Common\Result;
use App\Http\Controllers\Controller;
use App\Service\Circle\CircleService;
use App\Service\Circle\FriendCommentService;
use App\Service\Customer\CustomerService;
use App\Service\Easemob\EasemobService;
use App\Service\Jpush\JpushService;
use App\Service\ServiceLog;
use Illuminate\Support\Facades\Redis;

use App\Service\Circle\FriendPraiseService;
use Illuminate\Http\Request;

class CircleController extends Controller
{
    /**
     * 朋友圈首页
     */
    public function BestCirclePage(Request $request)
    {
        $page = $request->input('page');
        $uid = $request->input('uid');

        $offest = ($page-1)*10;
        //$page = $page*10;
        
        $says = CircleService::getBestPage($uid,10,$offest);

        if($says){
            Result::msg('0',"success",$says);
        }else{
            Result::msg('-18',"error","没有更多了");
        }
    }

    /**
     * 附近的求购
     */
    public function nearCircle(Request $request)
    {
        $uid = $request->input('uid');
        $lon = $request->input('lon');
        $lat = $request->input('lat');
        $page = $request->input('page');

        $offset = ($page-1)*10;
        $result = CircleService::getNearCircle($uid,$lon,$lat,$offset);
        if($result){
            Result::msg('0',"success",$result);
        }else{
            Result::msg('-18',"error","没有更多了");
        }
    }

    /**
     *发布朋友圈
     */
    public function pushFriendCircle(Request $request)
    {
        $uid = $request->input('uid');
        $content = $request->input('contents');
        $photos = $request->input('pictures');
        $lon = $request->input('lon');
        $lat = $request->input('lat');
        $location = $request->input('loca');
        $qiniu_config = config("qiniu.qiniu");
		
        //处理照片url
        if(!empty($photos)){
            $photos = json_decode($photos);
            foreach($photos as $key=>$value){
                $photos[$key] = $qiniu_config['imgPath'].$value;
            }
            $photos = json_encode($photos);
        }

        try {
            if (!CustomerService::findUser(['uid' => $uid])) {
                Result::msg('-16', "error", "无有效用户信息");
            }
            if (!$content) {
                Result::msg('-30', "error", "内容不能为空");
            }
            $data = array(
                'uid' => $uid,
                'content' => $content,
                'photos' => $photos,
                'lon' => $lon,
                'lat' => $lat,
                'location' => $location,
                'created_at' => date("Y-m-d H:i:s",time()),
            );

            if($friend_id = CircleService::addFriendCircle($data)){
				//加入redis缓存
				Redis::sadd('workslistids', "friends:{$friend_id}");
				Redis::hmset("friends:{$friend_id}",
                    "author_uid", "{$uid}",
                    "content", "{$content}",
                    "photos", "{$photos}",
                    "location", "{$location}",
                    "read_num", 0,
                    "comment_num", 0,
                    "share_num", 0,
                    "class", 4,  //1代表是动态
                    "id","{$friend_id}",
                    "aclass",0,
                    "price",0,
                    "created","{$data['created_at']}");
                //Redis::geoadd('qiugou',$lon,$lat,"friend".$last_id);

                Result::msg('0','success',$data);
                
            }else{
                Result::msg('-11','error','更新失败');
            }
            }catch (\Exception $e)
            {
                ServiceLog::record("debug.txt",$e->getMessage(),'error');
                Result::msg('-888','error','网络出错了');
            }
    }

	/**
     * 删除动态
     */
    public function cancleFriendCircle(Request $request)
    {
        Result::isEmpty($request->circleid,'无有效朋友圈','-34');
		Result::isEmpty($request->uid,'无有效信息','-31');

        $circle_info = CircleService::findFriendCircle([
            'id' => $request->circleid
        ]);
        if($circle_info->uid != $request->uid){
            Result::msg('-35','error','不能删除别人的动态');
        }
		
        try{
            if(!CircleService::removeCircle($request->circleid))
            {
                Result::msg('-11','error','更新失败');
            }
            Redis::srem('workslistids',"friends:{$request->circleid}");
            Redis::del("friends:{$request->circleid}");
            $data = array();
            Result::msg('0','success',$data);
        } catch (\Exception $e){
            ServiceLog::record("debug.txt",$e->getMessage(),'error');
            Result::msg('-888','error','网络出错了');
        }
    }
	
    /**
     * 朋友圈点赞
     */
    public function friendCirclePraise(Request $request)
    {
        $uid = $request->uid;
        $circle_id = $request->circleid;

        try {
            $parise_info = FriendPraiseService::getPraise([
                'uid' => $uid,
                'circleid' => $circle_id
            ]);


        if ($parise_info) {
            Result::msg('-13', 'error', '你已经点赞过了');
        }

        $data = [
            'uid' => $uid,
            'circleid' => $circle_id,
            'created_at' => date("Y-m-d H:i:s",time()),
        ];

        if (!FriendPraiseService::addPraise($data)) {
            Result::msg('-14', 'error', '点赞失败');
        }
        CircleService::addCirclePraiseNum($circle_id);
        Result::msg('0', 'success', $data);
        } catch (\Exception $e){
            ServiceLog::record("debug.txt",$e->getMessage(),'error');
            Result::msg('-888','error','网络出错了');
        }
    }

    /**
     * 朋友圈评论
     */
    public function comment(Request $request)
    {
        Result::isEmpty($request->uid,'无有效用户信息','-16');
        Result::isEmpty($request->circleid,'无有效信息','-31');
        Result::veryShort($request->comment);

        $data = array(
            'uid' => $request->uid,
            'circleid' => $request->circleid,
            'rid' => $request->rid,
            'content' => $request->comment
        );
        //获得朋友圈详情
        $circle_info = CircleService::findFriendCircle([
            'id' => $request->circleid
        ]);
        //获得评论
        if($request->rid!=0){

            $comment_info = FriendCommentService::getComments($request->rid);
            if(!$comment_info){
                Result::msg('-26','error','评论失效');
            }
            if($comment_info->uid == $request->uid){
                Result::msg('-25','error','不能回复自己');
            }
        }
        //添加评论
        if(!FriendCommentService::addComments($data)){
            Result::msg('-11','error','更新失败');
        }

        //获得官方账号扩展
//        $ext = Controller::getSendExt('sj_00000000000004');
//        //推送消息
//        if($request->rid){
//            $parent_info = CustomerService::findUser(['uid'=>$request->uid]);
//            $resmessage = "{$parent_info['nickname']}"."回复了你";
//            $ext['uid'] =  $circle_info['uid'];
//            $ext['push_class'] = 'friend_comment';
//            $ext['circle_id'] = $request->circleid;
//            $ext['rid'] = $request->rid;
//            JpushService::pushMessage($request->ruid,$resmessage,$data);
//        }else{
//            if($circle_info['uid'] != $data['uid']){
//                $parent_info = CustomerService::findUser(['uid'=>$request->uid]);
//                $resmessage = "{$parent_info['nickname']}"."评论了你的朋友圈";
//                $ext['uid'] =  $circle_info['uid'];
//                $ext['push_class'] = 'friend_comment';
//                $ext['circle_id'] = $request->circleid;
//                $ext['rid'] = 0;
//                JpushService::pushMessage($circle_info['uid'],$resmessage,$ext);
//            }
//        }


        CircleService::addCircleCommentNum($request->circleid);
        Result::msg('0','success',$data);

    }

    //获得评论列表
    public function getCommentsList(Request $request)
    {
        $circle_id = $request->input('circleid');
        $page = $request->input('page');
        $offset = ($page-1)*10;
        $data = FriendCommentService::getCommentsList($circle_id, $offset);
        if(!$data){
            Result::msg('-18',"error","没有更多了");
        }
        Result::msg('0','success',$data);
    }

    //获得回复
    public function getCommentsResponce(Request $request)
    {
        $rid = $request->input('rid');
        $page = $request->input('page');
        $offset = ($page-1)*10;
        $data = FriendCommentService::getCommentResponce($rid, $offset);
        if(!$data){
            Result::msg('-18',"error","没有更多了");
        }

        Result::msg('0',"success",$data);
    }

    /**
     * 增加阅读量
     * @param Request $request
     */
    public function addReading(Request $request)
    {
        $circle_id = $request->circleid;
        CircleService::addCircleReadingNum($circle_id);
        Result::msg('0',"success",[]);
    }

	//获得我发布的朋友圈
    public function getMyPushCircle(Request $request)
    {
        Result::isEmpty($request->uid,'无有效信息',-31);
        $page = $request->input('page');
		$offset = ($page-1)*10;
		//$page = $page*10;
        
        $data = CircleService::getMyPushCircle($request->uid, 10, $offset);
        if(!$data){
            Result::msg('-18',"error","没有更多了");
        }

        Result::msg('0',"success",$data);
    }
	
	/**
     * 小程序朋友圈展示
     */
    public function xcxCirclePage(Request $request)
    {
        $page = $request->input('page');
        $uid = $request->input('uid');

        $offest = ($page-1)*10;
        //$page = $page*10;
        
        $says = CircleService::getBestPage($uid,10,$offest);
		
		foreach($says as $say){
			$say->topic_image = json_decode($say->topic_image);
		}
		
		
        if($says){
            Result::msg('0',"success",$says);
        }else{
            Result::msg('-18',"error","没有更多了");
        }
    }
}